<script>
import { reactive, onMounted, getCurrentInstance, ref, toRaw} from 'vue'
import util from '../utils/util'
export default {
  name: 'User',
  setup () {
    // usrids的集合
    const userids = ref([])
    // 用户表单
    const user = reactive({
      state: 1
    })
    // 表格列的配置
    const columns = reactive([
      {
        label: '用户ID',
        prop: 'userId'
      },
      {
        label: '用户名',
        prop: 'userName'
      },
      {
        label: '用户邮箱',
        prop: 'userEmail'
      },
      {
        label: '用户角色',
        prop: 'role',
        formatter(row, col, value) {
          return {
            0: '管理员',
            1: '普通用户'
          }[value]
        }
      },
      {
        label: '用户状态',
        prop: 'state',
        formatter(row, col, value) {
          return {
            1: '在职',
            2: '离职',
            3: '试用期'
          }[value]
        }
      },
      {
        label: '注册时间',
        prop: 'createTime',
        formatter(row, col, val) {
          return util.formateDate(new Date(val))
        }
      },
      {
        label: '最后登录时间',
        prop: 'lastLoginTime',
        formatter(row, col, val) {
          return util.formateDate(new Date(val))
        }
      }
    ])
    // 用户列表的数据
    const userList = ref([
      {
        "state": 1,
        "role": "0",
        "roleList": [
          "60180b07b1eaed6c45fbebdb",
          "60150cb764de99631b2c3cd3",
          "60180b59b1eaed6c45fbebdc"
        ],
        "deptId": [
          "60167059c9027b7d2c520a61",
          "60167345c6a4417f2d27506f"
        ],
        "userId": 1000002,
        "userName": "admin",
        "userEmail": "admin@jason.com",
        "createTime": "2021-01-17T13:32:06.381Z",
        "lastLoginTime": "2021-01-17T13:32:06.381Z",
        "__v": 0,
        "job": "前端架构师",
        "mobile": "17611020000"
      }
    ])
    // 当前组件的实例
    const {proxy} = getCurrentInstance()
    onMounted(() => {
      getUserList()
      getRoleList()
      getDeptList()
    })
    // 分页配置
    const pager = reactive({
      pageNum: 1,
      pageSize: 10,
      total: 10
    })
    // 获取用户列表数据
    const getUserList = async () => {
      let params = {...user, ...pager}
      const {page, list} = await proxy.$api.userList(params)
      userList.value = list
      pager.total = page.total
    }
    // 查询功能
    const handleQuery = () => {
      getUserList()
    }
    // 重置功能
    const handleReset = (form) => {
      proxy.$refs[form].resetFields()
    }
    // 分页功能
    const handleCurrentChange = (val) => {
      pager.pageNum = val
      getUserList()
    }
    // 删除功能
    const handelDelete = async (row) => {
      const res = await proxy.$api.userDelete({
        userIds: [row.userId]
      })
      
      if (res.modifiedCount > 0) {
        proxy.$message.success('删除成功')
        getUserList()
      } else {
        proxy.$message.error('删除失败')
      }
    }
    
    // 批量删除
    const handlePatchDelete = async () => {
      console.log(userids.length);
      
      if (userids.value.length === 0) {
        proxy.$message.error('请勾选要删除的用户')
        return
      }
      const res = await proxy.$api.userDelete({
        userIds: userids.value
      })
      if (res.modifiedCount > 0) {
        proxy.$message.success('删除成功')
        getUserList()
      } else {
        proxy.$message.error('删除失败')
      }
    }
    
    // 勾选复选框的回调函数
    const handleSelectionChange = (res) => {
      let arr = []
      res.forEach(item => {
        arr.push(item.userId)
      })
      userids.value = arr
    }
    const showModal = ref(false)
    const userForm = reactive({
      state: 1
    })
    // 新增用户
    const add = () => {
      action.value = 'add'
      showModal.value = true
    }
    // 新增表单验证规则
    const rules = reactive({
      userName: [
        {
          required: true,
          message: '请输入用户名称',
          trigger: 'blur'
        }
      ],
      userEmail: [
        {
          required: true,
          message: '请输入用户邮箱',
          trigger: 'blur'
        }
      ],
      deptId: [
        {
          required: true,
          message: '请输入部门',
          trigger: 'blur'
        }
      ],
      mobile: [
        {
          pattern: /1[3-9]\d{9}/,
          message: '请输入正确的手机号格式',
          trigger: 'blur'
        }
      ]
    })
    // 获取角色列表
    const roleList = ref([])
    const getRoleList = async () => {
      const res = await proxy.$api.getRoleList()
      roleList.value = res
    }
    // 获取部门列表
    const deptList = ref([])
    const getDeptList = async () => {
      const list = await proxy.$api.getDeptList()
      deptList.value = list
    }

    const cancle = () => {
      showModal.value = false
      handleReset('dialogForm')
    }
    const action = ref('add')
    const confirm = () => {
      proxy.$refs.dialogForm.validate(async val => {
        if (val) {
          let params = toRaw(userForm)
          params.userEmail += '@jason.com'
          params.action = action.value
          let res = await proxy.$api.userSubmit(params)
          if (res) {
            if (action.value === 'edit') {
              proxy.$message.success('编辑用户成功')
            } else {
              proxy.$message.success('新增用户成功')
            }
            showModal.value = false   
            handleReset('dialogForm')
            getUserList()
          }
        }
      })
    }
    const editUser = (row) => {
      action.value = 'edit'
      showModal.value = true
      proxy.$nextTick(() => {
        row.state = Number(row.state)
        Object.assign(userForm, row)
      })  
    }
    return {
      user,
      columns,
      userList,
      handleQuery,
      handleReset,
      pager,
      handleCurrentChange,
      handelDelete,
      handlePatchDelete,
      handleSelectionChange,
      showModal,
      userForm,
      add,
      rules,
      roleList,
      deptList,
      cancle,
      confirm,
      editUser,
      action
    }
  }
}
</script>

<template>
  <div class="user-manage">
    <div class="query-form">
      <el-form :inline="true" :model="user" ref="form">
        <el-form-item label="用户ID" prop="userId">
          <el-input v-model="user.userId" placeholder="请输入用户ID" />
        </el-form-item>
        <el-form-item label="用户名" prop="userName">
          <el-input v-model="user.userName" placeholder="请输入用户名称" />
        </el-form-item>
        <el-form-item label="用户状态" prop="state">
          <el-select v-model="user.state">
             <el-option :value="0" label="所有" />
             <el-option :value="1" label="在职" />
             <el-option :value="2" label="离职" />
             <el-option :value="3" label="试用期" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="handleReset('form')">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="base-table">
      <div class="action">
        <el-button type="primary" @click="add">新增</el-button>
        <el-button type="danger" @click="handlePatchDelete">批量删除</el-button>
      </div>
      <el-table 
        :data="userList" 
        @selection-change="handleSelectionChange"
        >
        <el-table-column type="selection" width="55" />
        <el-table-column 
          v-for="item in columns" 
          :key="item.prop" 
          :prop="item.prop" 
          :label="item.label" 
          :width="item.width"
          :formatter="item.formatter"
        />
        <el-table-column fixed="right" label="Operations" min-width="120">
          <template #default="scope">
            <el-button type="primary" size="mini" @click="editUser(scope.row)">
              编辑
            </el-button>
            <el-button type="danger" size="mini" @click="handelDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination 
        background 
        class="pagination" 
        layout="prev, pager, next" 
        :total="pager.total" 
        @current-change="handleCurrentChange"
      />
    </div>
    <el-dialog
      :title="action === 'add' ? '新增用户' : '编辑用户'"
      v-model="showModal"
    >
      <el-form
        :model="userForm"
        label-width="100px"
        :rules="rules"
        ref="dialogForm"
      >
        <el-form-item
          prop="userName"
          label="用户名"
        >
          <el-input 
            placeholder="请输入用户名称"
            v-model="userForm.userName"
            :disabled="action === 'edit'"
          />
        </el-form-item>
        <el-form-item
          prop="userEmail"
          label="邮箱"
        >
          <el-input 
            placeholder="请输入用户邮箱"
            v-model="userForm.userEmail"
            :disabled="action === 'edit'"
          >
            <template #append>@jason.com</template>
          </el-input>
        </el-form-item>
        <el-form-item
          prop="mobile"
          label="手机号"
        >
          <el-input 
            placeholder="请输入手机号"
            v-model="userForm.mobile"
          />
        </el-form-item>
        <el-form-item
          prop="job"
          label="岗位"
        >
          <el-input 
            placeholder="请输入岗位"
            v-model="userForm.job"
          />
        </el-form-item>
        <el-form-item
          prop="state"
          label="状态"
        >
          <el-select v-model="userForm.state">
            <el-option :value="1" label="在职"/>
            <el-option :value="2" label="离职"/>
            <el-option :value="3" label="试用期"/>
          </el-select>
        </el-form-item>
        <el-form-item
          prop="roleList"
          label="系统角色"
        >
          <el-select 
            v-model="userForm.roleList"
            placeholder="请选择用户角色"
            multiple
            style="width: 100%"
          >
            <el-option v-for="item in roleList" :key="item._id" :label="item.roleName" :value="item._id"/>
          </el-select>
        </el-form-item>
        <el-form-item
          prop="deptId"
          label="部门"
        >
          <el-cascader 
            v-model="userForm.deptId"
            placeholder="请选择所属部门"
            :options="deptList"
            :props="{checkStrictly: true, value: '_id', label: 'deptName'}"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="cancle">取消</el-button>
        <el-button type="primary" @click="confirm">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.base-table {
  height: calc(100vh - 162px);
  overflow: auto;
}
</style>
